home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
The CICA Windows Explosion!
/
The CICA Windows Explosion! - Disc 2.iso
/
programr
/
brainw32.zip
/
README.TXT
Wrap
Text File
|
1994-04-29
|
30KB
|
757 lines
------------------------------------------------------------------------------
Code distribution for the book:
"Win32 System Services: The Heart of Windows NT"
by Marshall Brain
Published by Prentice Hall, ISBN 0-13-097825-6
To order a copy of the book call 1-800-947-7700
Copyright 1994, by Prentice Hall.
Version 1.1, April 29, 1994.
------------------------------------------------------------------------------
INTRODUCTION -
The "code" directory contains all of the code found in the book "Win32
System Services: The Heart of Windows NT", by Marshall Brain, published by
Prentice Hall. This code is being distributed so that you can work with the
examples in the book without having to retype them.
If you have any questions or comments, you can send them to the
following email address: "comments@iftech.com". Additional source
code, examples, and corrections are also available by email by
sending an empty message to "info@iftech.com". These are internet
email addresses--you can reach the internet through Compuserve,
MCI mail, and many other services. Consult your specific mail service
for details.
The following copyright notice applies to all information found
in this distribution:
Copyright 1994, by Interface Technologies, Inc.
You are free to copy and distribute this package for personal,
non-commercial uses provided that this readme file and copyright
notice remain with the package. There is no warranty, either
expressed or implied, supplied with any of the code or information
found in this distribution.
UNPACKING THE ZIP FILE -
When you unzip this distribution, be sure that you use the "-d"
option so that the directory structure gets restored correctly.
COMPILING THE CODE -
Each directory on this disk has its own makefile. Many of the
directories contain multiple source files and only one makefile--in
these directories, you can edit the APP variable to compile
each different code file (see individual makefiles for examples).
Before you can use the makefiles, you need to set some environment
variables. This is most easily done by opening a command shell and
typing "\mstools\setenv" (search for "setenv.bat" if you have trouble
finding the file). This batch file sets specific environment variables
to needed values.
Each directory has its own README.TXT file. Read this file for
special compilation instructions before trying to compile or run
the code.
To compile the code, cd into a specific code directory and type
"nmake". Compilation is automatic. If you encounter problems either
in finding things or compiling the code, it is probably because
Microsoft changed or moved things. Send mail to the "info" address
given above to find updated compilation instructions.
More detailed compiling instructions are given at the bottom of this
file in "Appendix A".
NOTE -
To get some of the MFC code to compile we had to modify one of the
/D options in ntsample.mak. Presumably this will get fixed
at some point but in case it doesn't, open ntsample.mak
and search for "/DWINVER=0x0300" and change it to
"/DWINVER=0x030A". This will cause the correct function
in one of the MFC header files to be included properly.
OTHER BOOKS IN THE SERIES
"Win32 System Services: The Heart of Windows NT" is the fourth
of a five book series on Windows NT programming and administration.
Other books in the series include:
- "Windows NT Programming: An Introduction Using C++"
ISBN 0-13-097833-7
- "Using Windows NT: The Essentials for Professionals"
ISBN 0-13-091977-2
- "Windows NT Administration: From Single Systems to
Heterogeneous Networks" ISBN 0-13-176694-5
- "Win32 System Services: The Heart of Windows NT"
ISBN 0-13-097825-6
To order a copy of any of these books, go through a local bookstore or
order by mail from Prentice Hall by calling 1-800-947-7700.
========================================================================
FROM THE PREFACE OF "WIN32 SYSTEM SERVICES: THE HEART OF WINDOWS NT"
The Win32 system services are the innovative, cutting-edge
capabilities that make Windows NT interesting and exciting. Amid all of
the media attention surrounding NT, you have probably heard and read
about many of the modern capabilities that this new operating system
contains:
Processes and threads
Synchronization
Remote Procedure Calls (RPCs)
Event logging
Network communications
TCP/IP networking with UNIX and OS/2 machines
File mapping
Interprocess communication
Compressed file access
Network drive and printer sharing
Serial communications
Services (background processing like UNIX daemons)
Object and file security
The goal of this book is to show you how to use all of these
different services in your own applications. This book contains
hundreds of concise, clear, and easy-to-understand example programs
and explanations. The examples show you how to access the system
services listed above, as well as many others. You can use these
examples directly to understand the concepts. You can also drop the
sample code into your own programs and then extend it to give your
applications new and useful features.
By learning about the many and varied system services available
inside of Windows NT, you can make your programs much more
interesting to the user. For example, if you learn about threads and then
add multiple threads to your applications, the user gets a much
smoother interface (see Chapter 5). Your program will also take
advantage of multiple processors on machines that have them. If you
add network support to your applications, then the user is able to
access network resources that are unavailable on a single machine (see
Chapter 7). If you add modem support, then you can use it to let the
user dial into a remote system (see Chapter 12). Or you might use a
modem to let the user dial a support line or registration system for a
product that your company sells.
The goal of this book is to give you a thorough and clear
understanding of the system services so that you can take advantage of
all of the capabilities that Windows NT has to offer.
AUDIENCE
This book is designed for two types of people. If you are a
devoted connoisseur or student of programming, the study of the
system functions is interesting in its own right. It's fun to see what is
available, and to try to think of ways to exploit those capabilities. One
way to use this book is to simply browse through it and see what is
possible. You can work with the examples and extend them in ways
that you find enjoyable.
If, on the other hand, you are a programmer with a deadline,
enjoyable entertainment is probably not your goal. You may have
looked at the huge number of functions in the Windows API and found
it discouraging. Where do you start? What you want is a set of useful
examples and clear explanations that quickly solve your specific
problems. You will find this book useful because it organizes concepts
logically and provides the material that you need to master a specific
topic very quickly.
If you are migrating from another operating system to Windows
NT, this book will help you to quickly map your existing knowledge into
the NT framework. See Chapter 1 for a list of the 100 most common
programming questions in Windows NT as well as the sections that
contain the answers.
ORGANIZATION
This book is organized by functional categories. For example,
Chapter 2 talks about all of the functions that pertain to File I/O and file
handling. Chapter 3 deals with disk drives. Chapter 4 discusses
directories. Chapter 5 talks about processes and threads. And so on.
You will find that each chapter starts with a general overview of the
topic, followed by sections that describe and give examples for subsets
of functions.
In many chapters you will find integrating examples that combine
different capabilities from several chapters to create larger applications.
Many of these larger examples form complete applications that you can
use as starting points for new projects of your own.
PHILOSOPHY
Several principles guide the design of this book. The first principle
is the most important and is therefore woven throughout: it is
simplicity. There is nothing worse than trying to look up a function,
only to find that its example is embedded within sample code that takes
three days to comprehend because it is 28 pages long. In all cases
functions are first demonstrated in code that is as simple as possible so
that you can extract the essence of each one very quickly. Then they
may also be integrated into larger examples. In many cases you will
look at the example code and say to yourself, "This is trivial!". That is
exactly the intent. If the book makes everything look simple and easy
for you, then it has accomplished its goal.
The second principle found in this book revolves around the idea
of functional families. Functions in the 32-bit API very rarely exist on
their own--it is far more common to find small collections of functions
that relate very closely to one another. For example, the ReadFile
function reads from a file, but you must open the file with CreateFile
before you can read from it, and then remember to close it with
CloseHandle afterwards (see Chapter 2). These functions belong to a
family. In this book you will generally find small groupings of functions
described as logical units.
The third principle in this book is currency. The Windows
API has been around for some time, and when you look at it you will
find that there is a certain layering. The documentation will often say
things like, "this function is retained for compatibility with version 1.8,
but has been superseded by function xyz." This book deals only with
the current functions, and leaves the superseded ones to die in peace.
The last principle guiding this book is independence. Each chapter
in this book is as stand-alone as possible, so that you can jump around
in the book as you please. In cases where material from other chapters
is important, you will find references to the related sections.
PREREQUISITES AND LANGUAGES
This book makes no assumptions about former knowledge of
systems programming in Windows or in any other system. It's only
real assumption is that you know C and/or C++. You will find that the
example code divides into two categories:
1) Text examples that run in "console mode". These programs run
from the MS-DOS prompt, accept keyboard input, and produce
text output. They form the vast majority of the code in this book
because they are simple. These programs are C++ compatible,
but the only elements really being used from C++ are the I/O
stream libraries.
2) "Windows" programs that use the Windows GUI. These
programs use C++ and the Microsoft Foundation Class library
(MFC). Book 2 in this series, "Windows NT Programming: An
Introduction using C++" describes how to create programs with
MFC, and will be helpful to you if you in understanding these
examples if you are not already familiar with MFC.
If you are a C programmer with no C++ experience, you will
have no trouble understanding the console programs. The only unusual
thing you will see is code that looks like this:
char s[100];
// Prompt the user
cout << "Enter a line of text: ";
// Read a line of text from the user
cin.getline(s,100);
// Echo the user's input to stdout
cout << s << endl;
This code declares a character string s, and then uses "cout <<"
to output a prompt to the user. The "cin.getline" statement reads a line
of text from the user. The final "cout" statement echos the line. The
book "Windows NT Programming: An Introduction using C++"
contains an extensive C++ appendix to help you get started with the
language if you are interested. It will also help you to understand the
MFC code.
CONTENTS OF THE BOOK
Each chapter in this book talks about a different service in the 32-
bit API. Chapter 1 contains a list of the 100 most common questions
about the system services, and it will help you to very quickly find
material that interests you. The list below summarizes the different
chapters in the book to help you with browsing.
o Chapter 1 is an introduction. It contains a list of the 100 most
common programming questions about the Windows NT system
services, and this list will serve as a good road map for you. The
chapter also contains general information that is useful throughout
the book.
o Chapter 2 discusses Files. It shows you how to open, read and
write files, how to read from compressed files, how to map files
into memory, and so on. The 32-bit API contains quite a few very
interesting file capabilities.
o Chapter 3 talks about the directory structure. It shows you how
to create and traverse directory trees.
o Chapter 4 introduces the drive structure of Windows NT. You
will learn how to query the drives on your local machine, and also
how to query and connect to drives on the network.
o Chapter 5 offers a complete introduction to processes and
threads in the NT environment. You will see how to multithread
your own applications, and the chapter shows you how to multi-
thread MFC applications as well. There is also a discussion of
processes, inter-process communication, and inheritance.
o Chapter 6 discusses NT's synchronization mechanisms. Critical
sections, mutexes, semaphores and events help you to write
multi-threaded code that does not step on itself. The chapter
introduces you to general synchronization principles and bugs, and
shows solutions to a number of standard problems. It also shows
you how to incorporate synchronization mechanisms into an MFC
program without stalling its event loop.
o Chapter 7 talks about network communications. NT contains
two different native technologies for communicating over the
network: mailslots and named pipes. NT also supports UPD and
TCP packets on TCP/IP networks. The latter capabilities let you
intercommunicate with UNIX and other TCP/IP machines. The
chapter includes a complete introduction to network principles and
terminology.
o Chapter 8 talks about Remote Procedure Calls, or RPCs. An RPC
lets you make a function call that is transmitted over the network
and executed on another machine. This chapter contains a
complete introduction to the hows and whys of RPCs, as well as
design principles to keep in mind when creating client/server
systems with RPCs. It contains examples of auto, implicit, explicit
and context binding, and also shows how to incorporate RPCs into
MFC programs.
o Chapter 9 discusses NT services. These are background
processes that start at boot time and run regardless of who is
logged in, just like daemons in UNIX. This chapter shows you how
to create your own services and install them in NT's service
manager. It also shows you how to place RPC servers into
services so they run continuously.
o Chapter 10 offers a complete introduction to the NT security
system. This system is uniform across all NT objects, so you learn
how to secure files, registry keys, pipes, semaphores, etc. It
teaches you everything you need to know to create and modify
access control lists and security descriptors.
o Chapter 11 discusses consoles, which you will use when you
want to create text-based programs in Windows NT. For example,
if you want to create a terminal emulator, consoles offer an easy
way to handle the keyboard input and character output for the
emulator.
o Chapter 12 talks about communications ports in NT systems. It
shows you how to access both the serial and parallel ports, and
demonstrates a simple terminal emulator and bulletin board
system.
o Chapter 13 shows you how to access system information, and
how to log users off and shutdown or reboot the system. For
example, this chapter shows you how to determine how many
CPUs a system contains, or how many buttons there are on the
mouse.
o Chapter 14 shows you how to modularize your programs using
dynamic link libraries (DLLs). Windows NT can be thought of as an
extensible operating system because of DLLs. A programmer can
easily add capabilities that others can use by creating a DLL and
publishing its interface. NT itself places much of its functionality in
DLLs.
o Chapter 15 contains short discussions and examples on six
miscellaneous topics: the registry, the event log, the NT time
model, error handling, structured exception handling, and the
memory model.
o Appendix A shows you how to compile the different types of
code found in the book.
o Appendix B contains information on contacting the authors via
Email to ask questions and retrieve free supplements and updates
to this book.
========================================================================
FROM Appendix A AND B OF "WIN32 SYSTEM SERVICES: THE HEART OF WINDOWS NT"
Appendix A
Compiling the Code in this Book
This book contains hundreds of listings. You will find that these
listings break down into four different categories:
1) Pure console programs that read and write text data
2) GUI programs using the 32-bit API
3) GUI programs using MFC
4) Other programs: DLL code, RPC code, etc.
This appendix contains information on compiling the first three
types of code using the Win32 SDK or Visual C++ for Windows NT. The
fourth type of code is covered when the code appears. For example, the
RPC chapter contains makefiles for using the MIDL compiler and
compiling RPC programs. You compile these programs using the same
techniques that you use to compile the first three categories of code.
The supplied diskette contains appropriately adjusted makefiles
for the code in each directory. This saves you the trouble of creating your
own. Look through this appendix to learn about how those makefiles
work and how to use them.
If you have compilation problems, be sure to contact the
information server described in Appendix B to obtain free updates.
A.1 COMPILING WITH THE WIN32 SDK
The code in Listing A.1 represents a typical console program
named textsamp.cpp. The makefile in Listing A.2 will compile it. Note
that the makefile's first line reads "APP=textsamp". Change the name
in this line to compile different programs.
// textsamp.cpp
#include <windows.h>
#include <iostream.h>
void main(void)
{
int x;
for (x=0; x<10; x++)
{
cout << "Hello" << endl;
Beep(100, 50);
Sleep(250);
}
}
Listing A.1
A simple console program (textsamp.cpp)
APP=textsamp
NODEBUG=1
!include <ntwin32.mak>
$(APP).exe: $(APP).obj
$(link) $(conlflags) $(ldebug) \
$(conlibsmt) $(APP).obj -out:$(APP).exe
$(APP).obj: $(APP).cpp
$(cc) $(cflags) $(cdebug) \
$(cvarsmt) $(APP).cpp
Listing A.2
A makefile for Listing A.1 (textsamp.cpp). Run mstools\setenv.bat before trying to
compile, and then type "nmake" to compile. Change the first line to compile a different
file.
Before you can compile Listing A.1 with the makefile in Listing
A.2, you must set some environment variables. The easiest way to do
this is to run the file setenv.bat in the mstools directory. You might
also consider looking at which variables are set by setenv, and then
setting them permanently in your account using the System applet in
the Control Panel. Once the environment variables are set, create a new
directory, place Listings A.1 and A.2 in it, and then type "nmake" to
compile the code.
Note that in many cases you will have to add extra libraries to the
link line of the makefile. The library advapi32.lib is especially
popular. If your program will not link, expect missing libraries. For
example, to add the advanced API library to the makefile, change the
link line in the makefile so that it looks like this:
$(APP).exe: $(APP).obj
$(link) $(conlflags) $(ldebug) advapi32.lib \
$(conlibsmt) $(APP).obj -out:$(APP).exe
Certain programs in Chapters 3 and 4 also want to link to
mpr.lib. The mstools\lib directory contains all of the normal system
libraries: Use qgrep in the lib directory with the "-l" option to find which
libraries contain functions that you have trouble locating.
Also note that the makefile uses "convarsmt" and "conlibsmt".
These are multi-threaded versions of the libraries, and they guarantee
that multi-threaded code will work correctly.
To compile GUI applications created using the 32-bit API (as
opposed to MFC programs, which are described below), use the makefile
shown in Listing A.4. Listing A.3 contains winsamp.cpp, which
represents a typical GUI application with a winmain main function. It
simply displays a message box and quits. The "ranmon" programs in
Chapter 7 need this makefile.
// winsamp.cpp
#include <windows.h>
#include <iostream.h>
int WINAPI WinMain(HANDLE ghInstance,
HANDLE hPrevInstance, LPSTR lpCmdLine,
int nCmdShow)
{
Beep (100, 100);
MessageBox(NULL, "Sample message",
"Winsamp", MB_OK | MB_ICONHAND);
return 0;
}
Listing A.3
A typical Windows NT GUI program (winsamp.cpp)
APP=winsamp
NODEBUG=1
!include <ntwin32.mak>
$(APP).exe: $(APP).obj
$(link) $(guilflags) $(ldebug) \
$(guilibsmt) $(APP).obj -out:$(APP).exe
$(APP).obj: $(APP).cpp
$(cc) $(cflags) $(cdebug) \
$(cvarsmt) $(APP).cpp
Listing A.4
A makefile for Listing A.3
As with the console program, create a new directory. Place in it
Listing A.3 with the file name "winsamp.cpp" and Listing A.4 with the
file name "makefile". Type "nmake" to compile the code.
This book contains a number of MFC (Microsoft Foundations Class
library) programs. Listing A.5 represents a typical MFC program, and
Listing A.7 is its makefile. Listing A.6 is a DEF file for the program,
and is required.
// mfcsamp.cpp
#include <afxwin.h>
#define IDB_BUTTON 100
// Declare the application class
class CButtonApp : public CWinApp
{
public:
virtual BOOL InitInstance();
};
// Create an instance of the application class
CButtonApp ButtonApp;
// Declare the main window class
class CButtonWindow : public CFrameWnd
{
CButton *button;
public:
CButtonWindow();
~CButtonWindow();
afx_msg void HandleButton();
DECLARE_MESSAGE_MAP()
};
// The message handler function
void CButtonWindow::HandleButton()
{
Beep(700,500);
}
// The message map
BEGIN_MESSAGE_MAP(CButtonWindow, CFrameWnd)
ON_COMMAND(IDB_BUTTON, HandleButton)
END_MESSAGE_MAP()
// The InitInstance function is called once
// when the application first executes
BOOL CButtonApp::InitInstance()
{
m_pMainWnd = new CButtonWindow();
m_pMainWnd->ShowWindow(m_nCmdShow);
m_pMainWnd->UpdateWindow();
return TRUE;
}
// The constructor for the window class
CButtonWindow::CButtonWindow()
{
CRect r;
// Create the window itself
Create(NULL,
"CButton Tests",
WS_OVERLAPPEDWINDOW,
CRect(0,0,200,200));
// Get the size of the client rectangle
GetClientRect(&r);
r.InflateRect(-20,-20);
// Create a button
button = new CButton();
button->Create("Push me",
WS_CHILD|WS_VISIBLE|BS_PUSHBUTTON,
r,
this,
IDB_BUTTON);
}
// The destructor for the window class
CButtonWindow::~CButtonWindow()
{
delete button;
CFrameWnd::~CFrameWnd();
}
Listing A.5
A typical MFC program (mfcsamp.cpp)
NAME mfcsamp
DESCRIPTION 'demo code for MFC'
EXETYPE WINDOWS
STUB 'WINSTUB.EXE'
CODE PRELOAD MOVEABLE DISCARDABLE
DATA PRELOAD MOVEABLE MULTIPLE
HEAPSIZE 1024
STACKSIZE 4096
Listing A.6
A DEF file for the MFC program (mfcsamp.def)
# Change this path to match your system
!include c:\mstools\mfc\samples\ntsample.mak
# Change the following name to compile
# different files
FILENAME=mfcsamp
OBJS=$(FILENAME).obj
$(FILENAME).exe: $(OBJS) $(FILENAME).def
$(LINK) $(GUIFLAGS) -out:$(FILENAME).exe \
$(FILENAME).obj $(MFCLIB) $(GUILIBS)
Listing A.7
A makefile for the MFC program
Note that the makefile includes "ntsample.mak". Adjust the path
to this file to match the path on your machine.
To compile the code, create a new directory. Copy Listing A.5 into a
file named "mfcsamp.cpp". Copy Listing A.6 into a file named
"mfcsamp.def". Copy Listing A.7 into a file named "makefile". Type
"nmake" to compile the code. When you create programs of your own,
adjust the FILENAME value in the makefile and change the first two
lines of the DEF file.
Many of the larger MFC programs in this book also use an RC file
to handle their menus. The appropriate makefile for compiling these
MFC programs is shown in Listing A.8.
# Change this path to match your system
!include c:\mstools\mfc\samples\ntsample.mak
# Change the following name to compile
# different files
FILENAME=mandel2
OBJS=$(FILENAME).obj
$(FILENAME).exe: $(OBJS) mandel.res mandel.def
$(LINK) $(GUIFLAGS) -out:$(FILENAME).exe \
$(FILENAME).obj $(MFCLIB) $(GUILIBS) \
mandel.res
Listing A.8
A makefile for MFC programs that use RC files.
This makefile compiles the mandelbrot examples in Chapter 5. The
two references to "mandel.res" cause the makefile to compile
"mandel.rc". Change the name "mandel" to the name of your RC file to
compile other RC files. See Chapter 6 of Windows NT Programming: An
Introduction Using C++ for more information.
A.2 COMPILING WITH VISUAL C++
You can compile the code in this book using Visual C++ either by
creating new project files, or by loading the makefiles supplied on the
diskette as external makefiles. The latter option is much easier, so it is
discussed here.
Listing A.1 in the previous section represents a simple console
program. Listing A.2 is its makefile. You can either type these two files
in or copy them from the diskette that came with the book. To compile
this code under Visual C++ take the following steps:
1) Start Visual C++.
2) Since Visual C++ remembers any previously open project and its
files, go into the Project menu and choose the Close option if it is
available. Go into the File menu and choose the Close option as
many times as you are allowed. This clears out the old project and
its files.
3) Select the Open option in the Project menu. In this dialog,
change to the directory that contains the code contained in Listings
A.1 and A.2. Type "makefile." into the File Name field (or choose
"All Files" from the File Type list and double-click on "makefile").
4) You will see a dialog asking if you want to open the makefile as
an external makefile. Answer "Yes".
5) You will see an Options dialog. Enter a name for the EXE file in
the first field. Use the value from the APP variable (e.g. use
"textsamp.exe" here).
6) The code should compile without error using the Build option in
the Project menu. Run it with the Execute option in the Project
menu.
Follow the same steps for the other example files seen in Section
A.1.
To compile multiple files in the same directory, close the current
project using the Close option in the Project directory. Change the
APP or FILENAME value in the makefile. Load the modified makefile
using the Open option in the Project menu. In the Options dialog, set
the EXE name to match the FILENAME.
You should be able to compile all of the code presented in this book
using Visual C++, with the possible exception of the RPC code in
Chapter 8. Visual C++ for NT version 2.0 does not contain the MIDL
compiler, so there is no way to compile the IDL files. The SDK contains
the MIDL file however (midl.exe), and if you borrow it and place it in the
msvcnt\bin directory, you can compile RPC code without problems.
========================================================================
Appendix B
Contacting the Author
Windows NT, like all operating systems, will change over time. We
want to keep your copy of the book current by providing you with
correction and update pages via electronic mail. If you find errors in the
book, or if you have any questions, comments, or suggestions for
improving the book, we would like to hear from you. Your comments will
help us improve later editions, and we'll post your corrections so other
readers can take advantage of them.
You can contact the author either by US mail or by electronic mail.
Electronic mail is preferred. The US mail address is:
Interface Technologies
P.O. Box 841
Zebulon, NC 27597
To send suggestions, comments, or corrections via electronic mail,
address e-mail to:
comments@iftech.com
To ask a question, send e-mail to:
questions@iftech.com
To request a list of the available update and correction pages, as
well as supplements, send e-mail to:
info@iftech.com
In the last case, the message can contain anything or nothing at
all. The mail system will send an automated reply with a list of topics
and further instructions.
These e-mail addresses are on the Internet and will suffice on mail
systems connected directly to the Internet. If you are using Compuserve,
you can add the prefix "INTERNET:" to the address to get your message
onto the Internet. For example:
INTERNET:comments@iftech.com
Other mail services such as MCImail, as well as many PC bulletin
boards, also offer Internet access. See the documentation for your
specific system for details.